<template>  
  <div class="chat-container">  
    <h1>自动回复机器人</h1>  <button @click="uploadDocx">更新后台文件</button>
    <div class="chat-window">  
      <div class="messages" v-for="message in messages" :key="message.id">  
        <div class="message"   
             :class="{'user': message.sender === 'user', 'bot': message.sender === 'bot'}"   
             :style="{ width: message.width + 'px' }">  
          {{ message.text }}  
        </div>  
      </div>  
    </div>  
    <div class="custom-select" @click="toggleDropdown">
      <div class="selected-option">{{ selectedOption }}</div>
      <span style="position: absolute;top: 1px;left: 130px;color: red;">选择提问的模块，以获取更准确的回答</span>
      <div class="options" v-if="dropdownOpen">
        <div class="option" v-for="option in options" :key="option"  @click="selectOption(option)">
          {{ option }}
        </div>
      </div>
    </div>
    <input v-model="userInput" @keyup.enter="sendMessage" placeholder="输入您的问题..." />  
    <button class="send-button" @click="sendMessage">发送</button>  
  </div>  
</template>  

<script>  
import { getRobotReply ,uploadDocxForAI} from '@/api/robot';  
import {addLog,getLogList} from '@/api/log';
import {jwtDecode} from 'jwt-decode';

export default {  
  data() {  
    return {  
            logItem:{
        mn:'',
        opn:'',
        res:'',
      },
      userInput: '',  
      selectedOption: '',
      dropdownOpen: false,
      options: ['部门管理' , '职位管理', '人员管理','任务管理', '我的任务','日程管理', '我的日程',
       '会议室管理', '通知管理','通知列表','请假管理','请假列表','考勤管理','报表列表','审批管理','文件管理'],
      messages: [],  
      defaultWidth: 154 // 设置消息气泡的默认宽度  
    };  
  },  
  created() {
    // Initialize options based on user role
    const userOptions = ['部门管理' , '职位管理', '人员管理','任务管理', '我的任务','日程管理', '我的日程',
       '会议室管理','通知列表','请假管理','请假列表','考勤管理','文件管理'];
    
    const token = localStorage.getItem('token');

console.log("1");
      const decodedToken = jwtDecode(token);
      if (decodedToken.role === 'SUPERMAN' || decodedToken.role === 'MANAGER') {
        console.log("2");
        return this.options;
      } else {
        // Filter out restricted options for non-manager roles
        console.log("3");
        this.options = userOptions;
      }

  },
  watch:{
    "selectedOption"(){
      this.logItem.mn = "selectedOption";
      this.logItem.opn = "选择询问的模块"+this.selectedOption;
      this.logItem.res = "true";
      addLog(this.logItem);
    }
  },
  methods: {  
    uploadDocx(){
      uploadDocxForAI().then((response)=>{
        this.$message.success(response.data);  
      this.logItem.mn = "uploadDocx";
      this.logItem.opn = "更新自动机器人文件";
      this.logItem.res = "true";
      addLog(this.logItem);
      }).catch((error)=>{
      this.logItem.mn = "uploadDocx";
      this.logItem.opn = "更新自动机器人文件";
      this.logItem.res = "false";
      addLog(this.logItem);
        this.$message.error('后台文件更新失败');  
      })
  },
    toggleDropdown() {  
      this.dropdownOpen = !this.dropdownOpen;  
    },
    selectOption(option) {
      this.selectedOption = option;
      this.dropdownOpen = false; // 选择后关闭下拉
      this.toggleDropdown();
    },
    sendMessage() {  
  if (this.userInput.trim() === '') return;  

  // 添加用户消息  
  this.messages.push({   
    id: Date.now(),   
    text: this.userInput,   
    sender: 'user',   
    width: this.calculateWidth(this.userInput)   
  });  
  const currentInput = this.userInput; // 保存当前输入的值  

  // 清空输入框  
  this.userInput = '';  

  // 显示加载中的消息气泡  
  const loadingMessage = {  
    id: Date.now() + 1, // 使用不同的ID确保唯一  
    text: '正在加载回复...',  
    sender: 'bot',  
    width: this.defaultWidth  
  };  
  this.messages.push(loadingMessage);   

  // 模拟机器人的自动回复  
  setTimeout(() => {  
    // 获取机器人回复  
    this.getBotReply(currentInput, this.selectedOption, loadingMessage);  
  }, 500);  
},  

getBotReply(input, selectedOption, loadingMessage) {   
  input = `"${input}"` // 接收选项参数  
  const requestData = {  
    input: input,  
    option: selectedOption // 将选项添加到请求体  
  };  
  console.log("请求体", requestData);  
  
  getRobotReply(requestData).then((response) => {  
    console.log("回复", response.data);  
      this.logItem.mn = "getRobotReply";
      this.logItem.opn = "用户提问"+requestData.input;
      this.logItem.res = "true";
      addLog(this.logItem);
    const botReply = response.data;  
    
    // 移除加载中的消息气泡  
    const loadingIndex = this.messages.indexOf(loadingMessage);  
    if (loadingIndex > -1) {  
      this.messages.splice(loadingIndex, 1);  
    }  
    
    this.messages.push({ id: Date.now(), text: botReply, sender: 'bot', width: this.calculateWidth(botReply) });  
  }).catch(error => {  
    console.error("获取机器人回复时出错", error);  
    this.logItem.mn = "getRobotReply";
    this.logItem.opn = "用户提问"+requestData.input;
    this.logItem.res = "false";
    addLog(this.logItem);
    const ans = "抱歉，我无法获取回复,请前往" + `"${selectedOption}"` + "查看";  
    
    // 移除加载中的消息气泡  
    const loadingIndex = this.messages.indexOf(loadingMessage);  
    if (loadingIndex > -1) {  
      this.messages.splice(loadingIndex, 1);  
    }  

    this.messages.push({ id: Date.now(), text: ans, sender: 'bot', width: this.defaultWidth });  
  });  
},  

    calculateWidth(text) {  
      // 计算消息气泡宽度，可以根据字符长度动态调整  
      // const minWidth = 100; // 设置气泡的最小宽度  
      const maxWidth = 400;  
      const additionalWidth = Math.min(text.length * 15, maxWidth); // 按字符长度计算的额外宽度，确保不小于最小宽度  
      return additionalWidth; // 计算总宽度  
    }  
  }  
}  
</script>  

<style>  
.chat-container {  
  width: 90%;  
  margin: 0 auto;  
  border: 1px solid #ccc;  
  border-radius: 10px;  
  padding: 20px;  
  background-color: #f9f9f9;  
}  

.chat-window {  
  height: 500px;  
  overflow-y: auto;  
  border: 1px solid #ddd;  
  border-radius: 5px;  
  padding: 10px;  
  margin-bottom: 10px;  
  background-color: #fff;  
  display: flex;  
  flex-direction: column;  
}  

.messages {  
  margin: 10px 0;  
  display: flex;  
  flex-direction: column;  
}  

.message {  
  padding: 8px;  
  border-radius: 5px;  
  margin-bottom: 5px;  
  word-wrap: break-word; /* 允许换行以适应宽度 */  
  transition: width 0.2s; /* 添加过渡效果 */  
  display: inline-block; /* 将消息气泡设置为行内块元素以适应宽度 */  
  text-align: left; /* 确保文本左对齐 */  
}  

.user {  
  background-color: #d1e7dd;  
  text-align: left; /* 确保用户气泡文本左对齐 */  
  margin-left: auto; /* 将用户气泡推到右侧 */  
  align-self: flex-end; /* 确保用户气泡在右侧显示 */  
}  

.bot {  
  background-color: #f8d7da;  
  text-align: left; /* 确保机器人气泡文本左对齐 */  
  margin-right: auto; /* 将机器人气泡推到左侧 */  
}  

input {  
  width: calc(100% - 80px);  
  padding: 10px;  
  border-radius: 5px;  
  border: 1px solid #ccc;  
}  

.send-button {  
  padding: 10px;  
  margin-left: 10px;  
  border-radius: 5px;  
  border: none;  
  background-color: #007bff;  
  color: white;  
  cursor: pointer;  
}  

button:hover {  
  background-color: #0056b3;  
}  

.custom-select {
  position: relative;
  cursor: pointer;
}

.selected-option {
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  background-color: #fff;
  width: 100px;
}

.options {
  position: absolute;
  bottom: 100%; /* 向上展开 */
  left: 0;
  right: 0;
  border: 1px solid #ccc;
  border-radius: 5px;
  background-color: #fff;
  z-index: 10;
  width: 130px;
  text-align: center;
}

.option {
  padding: 3px;
  cursor: pointer;
  width: 100px;
  text-align: center;
}

.option:hover {
  background-color: #f0f0f0;
  width: 100px;
}
</style>  